package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/middleware"
	"rock/customer/models"
)

// @Summary 创建群聊
// @Description 传参只需要传UserId
// @Tags 群组
// @ID /creategroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{data=dto.Groups} "success"
// @Router /creategroup [post]
func (g *GroupController) createGroup(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//校验用户
	findUser, err := userService.UserByUserId(router, InstanceDB, params.UserId)
	if err != nil {
		dealRequestError(router, err)
		return
	}
	//
	groupId, err := queryUserJoinGroup(params)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//寻找群成员,返回之前群的数据
	if len(groupId) > 0 {
		queryParam := dto.Group{GroupId: groupId}
		responseData, err := queryGroupMember(queryParam)
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
		middleware.ResponseSuccess(router, responseData)
		return
	}
	//
	responseData, err := createGroupTransaction(router, params, groupId, findUser)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 创建私聊
// @Description 传参只需要传UserId，OtherUserId
// @Tags 群组
// @ID /createcsgroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{data=dto.Groups} "success"
// @Router /createcsgroup [post]
func (g *GroupController) createCsGroup(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	findUser := dto.UserDetail{}
	findOtherUser := dto.UserDetail{}
	// 校验私聊我方身份
	{
		csUser, err := customerServiceService.CsUser(router, InstanceDB, gconv.Int(params.UserId))
		if err != nil {
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
		}
		if csUser.UserId == 0 {
			tip := fmt.Sprintf("customer type is wrong")
			middleware.ResponseError(router, middleware.USER_NOT_EXIST, errors.New(tip))
			return
		}
		findUser = csUser
	}
	// 校验私聊对方身份
	{
		csUser, err := customerServiceService.CsUser(router, InstanceDB, gconv.Int(params.OtherUserId))
		if err != nil {
			if !errors.Is(err, gorm.ErrRecordNotFound) {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
		}
		if csUser.UserId == 0 {
			tip := fmt.Sprintf("customer type is wrong")
			middleware.ResponseError(router, middleware.USER_NOT_EXIST, errors.New(tip))
			return
		}
		findOtherUser = csUser
	}
	groupId := ""
	{
		groupCs, err := groupService.GroupCs(router, BusinessDB, params.UserId, params.OtherUserId)
		if err != nil {
			if err.Error() != initParam.DataIsNotExist {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
			groupCs = models.WkbGroup{}
		}
		if groupCs.GroupID != "" {
			groupId = groupCs.GroupID
		}
	}
	//寻找群成员,返回之前群的数据
	if len(groupId) > 0 {
		queryParam := dto.Group{GroupId: groupId}
		responseData, err := queryGroupMember(queryParam)
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
		middleware.ResponseSuccess(router, responseData)
		return
	}
	//
	reData, err := createCsGroupTransaction(router, params, groupId, findOtherUser, findUser)
	if err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}

	// 私聊创建成功，清除双方聊天列表缓存
	updateMessagesListCache(gconv.Int(params.UserId))

	//
	updateMessagesListCache(gconv.Int(params.OtherUserId))

	responseData := reData
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 解散群组
// @Description 传参只需要传UserId，GroupId
// @Tags 群组
// @ID /dismissgroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /dismissgroup [post]
func (g *GroupController) dismissGroup(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	queryParam := dto.Group{
		GroupId: params.GroupId,
		State:   3,
	}
	err := modifyGroupState(queryParam)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}

// @Summary 刷新群组信息
// @Description 传参只需要传GroupId，GroupName。当群组名称变更时,刷新群组信息后 5 分钟内生效，Push 推送时将显示刷新后的群组名称。
// @Tags 群组
// @ID /refreshgroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{data=[]dto.GroupRongCloudInfo} "success"
// @Router /refreshgroup [post]
func (g *GroupController) refreshGroup(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	// 刷新融云群组信息
	rcParam := fmt.Sprintf("groupId=%s&groupName=%s", params.GroupId, params.GroupName)
	rcReq, err := refreshRonGroup(rcParam)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//返回
	responseData := rcReq.Groups
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 修改群组状态 (完成)
// @Description 传参只需要传GroupId，State。当群组状态变成已完成时，系统会删除客服人员和FAE，该群只剩下客户和机器人
// @Tags 群组
// @ID /mgroupstate
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /mgroupstate [post]
func (g *GroupController) modifyGroupState(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//修改群状态
	err := groupService.UpdateGroupState(router, BusinessDB, params.GroupId, params.State)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//完成
	if params.State == int(models.GROUP_FINISH) || params.State == int(models.GROUP_FAIL_FINISH) {
		//
		DeleteHeap("invitation_" + params.GroupId)
		DeleteHeap("question_" + params.GroupId)
		//踢出群内的客服
		groupMemberCs, err := groupService.GroupMemberCs(router, BusinessDB, params.GroupId)
		if err != nil {
			dealRequestError(router, err)
			return
		}
		userId := ""
		// 保留群主
		//for k, v := range groupMember {
		//	if k > 0 {
		//		userId = userId + gconv.String(v.UserID) + ","
		//	}
		//}
		// 不保留群主
		for _, v := range groupMemberCs {
			userId = userId + gconv.String(v.UserID) + ","
		}
		if userId != "" {
			userId = userId[0 : len(userId)-1]
			queryParam := dto.Group{
				GroupId:  params.GroupId,
				UserId:   userId,
				QuitType: 3,
			}
			err = quitGroup(queryParam)
			if err != nil {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
		}
		//发送信息给到客户去做刷新
		err = send(dto.Group{
			GroupId: params.GroupId,
			MsgType: 22, //
		})
		if err != nil {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
		//
		record(router, params.GroupId, params.State)
		//
		middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
	} else {
		middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
	}
	//
	err = messageService.UpdateMessageCurrentStatus(router, BusinessDB, params.GroupId)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	err = addRedis(router, 1, initParam.BrowseCurrentPrefix + params.GroupId)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	//修改列表缓存
	updateRedis(router, params.GroupId)
}

// @Summary 查询私聊
// @Description 传参只需要传UserId，OtherUserId
// @Tags 群组
// @ID /checkcsgroup
// @Accept  json
// @Produce  json
// @Param polygon body dto.Group true "body"
// @Success 200 {object} middleware.Response{data=dto.Groups} "success"
// @Router /checkcsgroup [post]
func (g *GroupController) checkCsGroup(router *gin.Context) {
	params := &dto.Group{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	//
	findUser := dto.UserDetail{}
	findOtherUser := dto.UserDetail{}
	err := InstanceDB.Error
	groupId := ""
	if gconv.Int(params.UserId) != 0 && gconv.Int(params.OtherUserId) != 0 {
		// 校验私聊我方身份
		{
			csUser, err := customerServiceService.CsUser(router, InstanceDB, gconv.Int(params.UserId))
			if err != nil {
				if !errors.Is(err, gorm.ErrRecordNotFound) {
					middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
					return
				}
			}
			if csUser.UserId == 0 {
				tip := fmt.Sprintf("customer type is wrong")
				middleware.ResponseError(router, middleware.USER_NOT_EXIST, errors.New(tip))
				return
			}
			findUser = csUser
		}
		// 校验私聊对方身份
		{
			csUser, err := customerServiceService.CsUser(router, InstanceDB, gconv.Int(params.OtherUserId))
			if err != nil {
				if !errors.Is(err, gorm.ErrRecordNotFound) {
					middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
					return
				}
			}
			if csUser.UserId == 0 {
				tip := fmt.Sprintf("customer type is wrong")
				middleware.ResponseError(router, middleware.USER_NOT_EXIST, errors.New(tip))
				return
			}
			findOtherUser = csUser
		}
		//首先判断以这个用户为主的群聊是否已经存在,直接调融云接口查询
		{
			groupC, err := groupService.GroupC(router, BusinessDB, params.UserId, params.OtherUserId)
			if err != nil {
				if err.Error() == initParam.DataIsNotExist {
					responseData := &dto.Groups{
						GroupId:      "",
						GroupName:    "",
						GroupMembers: make([]dto.GroupMembers, 0),
					}
					middleware.ResponseSuccess(router, responseData)
					return
				}
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
			if groupC.GroupID != "" {
				groupId = groupC.GroupID
			}
		}
	} else {
		group, err := groupService.Group(router, InstanceDB, params.GroupId)
		if err != nil {
			dealRequestError(router, err)
			return
		}
		if group.GroupID != "" {
			groupId = group.GroupID
		}
	}
	//寻找群成员,返回之前群的数据
	if len(groupId) > 0 {
		queryParam := dto.Group{GroupId: groupId}
		responseData, err := queryGroupMember(queryParam)
		if err != nil {
			middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
			return
		}
		middleware.ResponseSuccess(router, responseData)
		return
	}
	//
	redisData, err := createCsGroupTransaction(router, params, groupId, findOtherUser, findUser)
	if err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	responseData := redisData
	middleware.ResponseSuccess(router, responseData)
}
